//
//  netease.swift
//  yiplayer
//
//  Created by cgw on 2024/5/7.
//

import Foundation
import CryptoSwift
import SwiftyRSA
import BigInt
  
class NeteaseApi {
    class func encodeNeteaseData(_ data: [String: Any]) -> String {
        let jsonData = try! JSONSerialization.data(withJSONObject: data, options: [])
        let key = Array<UInt8>.init(hex: "7246674226682325323F5E6544673A51")
        let encryptor = try! AES(key: key, blockMode: ECB(), padding: .pkcs7)
        
        let encryptedData = try! encryptor.encrypt(jsonData.bytes)
        return encryptedData.toHexString().uppercased()
    }
    
    class func encryptedRequest(para: [String: Any]) -> [String: String] {
        let MODULUS = "00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7"
        let PUBKEY = "010001"
        let NONCE = "0CoJUm6Qyw8W8jud"
        let data = para.toJsonString()!
        //let data1 = "{\"ids\": [2019709443], \"br\": 32000}"
        let secret = self.createKey()
        let text = self.aes(text: data, key: NONCE)
//        let params = self.aes(text: text, key: "d899538efa504778")//secret.toHexString())
        let params = self.aes(text: text, key: secret)
        let encseckey = self.rsa(text: secret, pubkeyhex16: PUBKEY, modulushex16: MODULUS)
        return ["params": params, "encSecKey": encseckey]
    }
  
    // 注意：这里省略了encrypted_request方法的部分实现，因为它需要完整的RSA加密实现
    class func aes(text: String, key: String) ->String{
        let kk = "0102030405060708"
        let encryptor = try! AES(key: key, iv: kk)
        return try! encryptor.encrypt(text.bytes).toBase64()
    }
    
    // 生成rsa的key
    class func rsa(text: String, pubkeyhex16: String, modulushex16: String) -> String{
        
        //16进制字符串->所有的assci值->转为16进制字符串
        func toHexFromHexAssci(hex: String) -> String{
            var hexstr = ""
            for char in hex {
                // 获取字符串中的每个字符的assci值
                if let av = char.asciiValue {
                    // 将assci值转16进制字符串
                    let hexchar = String(av, radix: 16)
                    hexstr += hexchar
                }
            }
            return hexstr
        }
        
        // 逆序
        let rtext = String(text.reversed())
        
        
//        let fromhex = "877405afe835998d"
//        let tohex = "38373734303561666538333539393864"
        
        
//        let rtext0 = "877405afe835998d"
        let x1 = toHexFromHexAssci(hex: rtext)
        
        let x = BigInt(x1, radix:16)!
        let y = BigInt(pubkeyhex16, radix: 16)!
        let z = BigInt(modulushex16, radix: 16)!
        
        let mod = x.power(y, modulus: z)
        let ret = String(mod, radix: 16)
        
        func padZero(numberString: String, toLength: Int) -> String {
            let len = numberString.count
            if len >= toLength {
                return numberString
            }
            let padding = String(repeating: "0", count: max(0, toLength - len))
            return padding + numberString
        }
        return padZero(numberString: ret, toLength: 256)
    }
    
    // 长度为16的16进制字符串
    class func createKey() -> String {
        func createRandomUint8Array(length: Int) -> [UInt8]? {
            guard length > 0 else { return nil } // 确保长度是正数
            var randomBytes = [UInt8](repeating: 0, count: length)
            let status = SecRandomCopyBytes(kSecRandomDefault, randomBytes.count, &randomBytes)
            if status != 0 {
                return nil // 如果生成随机字节失败，返回 nil
            }
            return randomBytes
        }
        
        if let b = createRandomUint8Array(length: 16)?.toHexString() {
            if b.count > 16 {
                return b.subTo(16)
            }
        }
        return "9b8272a8096df9"+String(arc4random()%9+1)+String(arc4random()%9+1)
    }
}
  
  

extension Dictionary{
    func toJsonString() -> String? {

        // 将字典转换为 JSON 数据
        if let jsonData = try? JSONSerialization.data(withJSONObject: self, options: []) {
            // 将 JSON 数据转换为字符串
            if let jsonString = String(data: jsonData, encoding: .utf8) {
                print(jsonString) // 输出 JSON 字符串
                return jsonString
            }
        }
        return nil
    }
}

extension String {
    func toJsonDic() -> [String: Any]?{
//        let jsonString = """
//        {
//            "name": "Alice",
//            "age": 30,
//            "city": "New York"
//        }
//        """
        let jsonString = self
        // 使用 JSONSerialization 将 JSON 字符串转换为 Data
        guard let jsonData = jsonString.data(using: .utf8) else {
            // fatalError("Could not create data from json string")
            return nil
        }
          
        // 使用 JSONSerialization 将 Data 转换为字典
        do {
            let jsonResult = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any]
            return jsonResult
        } catch {
            print("Failed to parse JSON")
            return nil
        }
    }
}
